package com.elitel.frame.base.service.impl;

import com.elitel.common.elasticSearch.ESClient;
import com.elitel.frame.base.component.RedisCacheComponent;
import com.elitel.frame.base.component.RedisCacheDataBase;
import com.elitel.frame.base.component.RedisCacheProjectService;
import com.elitel.frame.base.component.exportprojectdata.DataBaseConnInfo;
import com.elitel.frame.base.component.exportprojectdata.ElasticSerachInfo;
import com.elitel.frame.base.service.CfgExtsearchService;
import com.elitel.frame.main.dao.BaseSearchMapper;
import com.elitel.frame.main.dao.CfgExtsearchMapper;
import com.elitel.frame.main.dao.SysPrjserviceMapper;
import com.elitel.frame.main.dao.ext.ExtBaseSearchMapper;
import com.elitel.frame.main.dao.ext.ExtCfgExtsearchMapper;
import com.elitel.frame.main.dao.ext.ExtCfgFieldMapper;
import com.elitel.frame.main.entity.*;
import com.elitel.frame.main.entity.ext.CfgExtsearchExt;
import com.elitel.frame.main.entity.vo.FullTextSearchVo;
import org.apache.poi.ss.formula.functions.LinearRegressionFunction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * show 全文检索服务接口实现类
 * by date 2018/03/13 guoyanfei
 */
@Service
public class CfgExtsearchServiceImpl implements CfgExtsearchService {
    @Autowired
    private ExtCfgFieldMapper extCfgFieldMapper;
    @Autowired
    private CfgExtsearchMapper cfgExtsearchMapper;
    @Autowired
    private BaseSearchMapper baseSearchMapper;
    @Autowired
    private SysPrjserviceMapper sysPrjserviceMapper;
    @Autowired
    private ExtBaseSearchMapper extBaseSearchMapper;
    @Autowired
    private DataBaseConnInfo dataBaseConnInfo;
    @Autowired
    private RedisCacheProjectService redisCacheProjectService;
    @Autowired
    private ExtCfgExtsearchMapper extCfgExtsearchMapper;
    @Autowired
    private RedisCacheComponent redisCacheComponent;
    @Autowired
    private RedisCacheDataBase redisCacheDataBase;
    @Autowired
    private ElasticSerachInfo elasticSerachInfo;

    /**
     * show 通过表标识查询字段类型为String的字段信息
     * by date 2018/03/13
     *
     * @param dtConfigId 表标识
     * @return CfgField实体list集合
     * @author guoyanfei
     */
    @Override
    public List<CfgField> getFieldBydtconfig(String dtConfigId) {
        return extCfgFieldMapper.selectFieldTypeString(dtConfigId);
    }

    /**
     * show 通过guid查询全文检索配置服务信息
     * by date 2018/03/14
     *
     * @param guid 服务ID
     * @return CfgExtsearch实体
     * @author guoyanfei
     */
    @Override
    public CfgExtsearch getSearchByguid(String guid) {
        return cfgExtsearchMapper.selectByPrimaryKey(guid);
    }

    /**
     * show 新增全文检索基本服务信息(cfgextsearch)与配置信息(basesearch)服务接口
     * created by date 2018/03/16
     * 实现方法
     *
     * @param cfgExtsearchExt 全文检索扩展实体
     * @return 新增结果
     * @author guoyanfei
     */
    @Override
    public Integer addSearchInfo(CfgExtsearchExt cfgExtsearchExt) {
        Integer result = 0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowdate = dateFormat.format(new Date());

        //1、新增全文检索服务基本信息表
        CfgExtsearch cfgExtsearch = new CfgExtsearch();
        cfgExtsearch.setGuid(cfgExtsearchExt.getGuid());
        cfgExtsearch.setServicename(cfgExtsearchExt.getServicename());
        cfgExtsearch.setIndextype(cfgExtsearchExt.getIndextype());
        cfgExtsearch.setRemark(cfgExtsearchExt.getRemark());
        cfgExtsearch.setCreatedate(nowdate);
        cfgExtsearch.setCronexpression(cfgExtsearchExt.getCronexpression());
        cfgExtsearch.setStatus(0);

        result += cfgExtsearchMapper.insertSelective(cfgExtsearch);

        //2、新增全文检索配置信息表
        result += addBaseSearch(cfgExtsearchExt);

        //3、新增工程信息
        SysPrjservice sysPrjservice = new SysPrjservice();
        sysPrjservice.setGuid(UUID.randomUUID().toString());
        sysPrjservice.setPcode(cfgExtsearchExt.getPcode());
        sysPrjservice.setServicetype(cfgExtsearchExt.getServicetype());
        sysPrjservice.setServicecode(cfgExtsearchExt.getGuid());
        sysPrjservice.setCreatedate(new Date());
        result += sysPrjserviceMapper.insertSelective(sysPrjservice);

        //4、刷新Redis缓存
        redisCacheComponent.refreshCfgExtSearchRedisCache();
        redisCacheDataBase.refreshFullTextSearchVoRedisCache(cfgExtsearchExt.getGuid());

        return result;
    }

    /**
     * show 通过服务ID 查询全文检索服务配置信息
     * created by date 2018/03/14
     * 实现类
     *
     * @param serviceId 服务ID
     * @return BaseSearch实体List集合
     * @author guoyanfei
     */
    @Override
    public List<FullTextSearchVo> getBasesearchInfoByserviceId(String serviceId) {
        List<FullTextSearchVo> fullTextSearchVos = new ArrayList<>();
        String databaseType = dataBaseConnInfo.dataBaseType;

        /*switch (databaseType) {
            case "oracle":
                fullTextSearchVos = extBaseSearchMapper.getFullTextSearchVoByserviceIdOracle(serviceId);
                break;
            case "mysql":
            case "sqlite":
            case "h2":
            case DataSourceType.POSTGRES:
                fullTextSearchVos = extBaseSearchMapper.getFullTextSearchVoByserviceIdMysql(serviceId);
                break;
        }*/
        fullTextSearchVos = extBaseSearchMapper.getFullTextSearchVoByserviceIdMysql(serviceId);

        //设置字段对应的描述信息
        if (fullTextSearchVos != null && fullTextSearchVos.size() > 0) {
            for (FullTextSearchVo ft : fullTextSearchVos) {

                //1、查询检索字段描述信息及字段code
                List<CfgField> cfgFields = extCfgFieldMapper.selectFieldTypeString(ft.getDtConfigid());
                String fieldtext = getFieldCn(cfgFields, ft.getFieldid());
                ft.setFieldtext(fieldtext);
                String fieldcode = getFieldCode(cfgFields, ft.getFieldid());
                ft.setFieldidcode(fieldcode);

                //2、查询更新字段描述信息
                List<CfgField> cfgFields1 = extCfgFieldMapper.selectFieldByConfig(ft.getDtConfigid());
                String updatefieldtext = getFieldCn(cfgFields1, ft.getUpdatefield());
                ft.setUpdatefieldtext(updatefieldtext);
                String updatefieldcode = getFieldCode(cfgFields1, ft.getUpdatefield());
                ft.setUpdatefieldcode(updatefieldcode);

                //3、查询主键字段code
                String primaryfieldcode = getFieldCode(cfgFields1, ft.getPrimarykeyid());
                ft.setPrimarykeyidcode(primaryfieldcode);
            }
        }

        return fullTextSearchVos;
    }

    /**
     * show 修改全文检索服务基本信息(CFG_EXTSEARCH表)及配置信息(BASE_SEARCH表)
     * created by date 2018/03/14
     * 实现类
     *
     * @param cfgExtsearchExt 实体
     * @return 修改结果
     * @author guoyanfei
     */
    @Override
    public Integer updateSearchInfo(CfgExtsearchExt cfgExtsearchExt) {
        Integer result = 0;

        //1、修改检索服务基本信息表
        CfgExtsearch cfgExtsearch = new CfgExtsearch();
        cfgExtsearch.setGuid(cfgExtsearchExt.getGuid());
        cfgExtsearch.setServicename(cfgExtsearchExt.getServicename());
        cfgExtsearch.setRemark(cfgExtsearchExt.getRemark());
        cfgExtsearch.setCronexpression(cfgExtsearchExt.getCronexpression());
        cfgExtsearch.setStatus(0);
        result += cfgExtsearchMapper.updateByPrimaryKeySelective(cfgExtsearch);

        //2、删除已配置检索服务配置信息
        result += extBaseSearchMapper.deleteBasesearchByserviceId(cfgExtsearchExt.getGuid());

        //3、新增全文检索配置信息表
        result += addBaseSearch(cfgExtsearchExt);

        //4、刷新Redis缓存
        redisCacheComponent.refreshCfgExtSearchRedisCache();
        redisCacheDataBase.refreshFullTextSearchVoRedisCache(cfgExtsearchExt.getGuid());

        return result;
    }

    /**
     * show 批量新增全文检索配置信息
     * created by date 2018/03/14
     *
     * @param cfgExtsearchExt 实体
     * @return 新增结果
     * @author guoyanfei
     */
    private Integer addBaseSearch(CfgExtsearchExt cfgExtsearchExt) {
        Integer result = 0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowdate = dateFormat.format(new Date());

        //1、新增全文检索配置信息表
        for (BaseSearch bs : cfgExtsearchExt.getBaseSearches()) {
            bs.setCretedate(nowdate);
            bs.setCreateuser("admin");
            //设置主键字段ID
            List<CfgField> fieldPrimarykey = extCfgFieldMapper.selectPrimaryKeybydtconfigId(bs.getDtConfigId());
            if (fieldPrimarykey != null && fieldPrimarykey.size() > 0) {
                String primarykeys = "";
                for (CfgField cf : fieldPrimarykey) {
                    if (primarykeys.equals("")) {
                        primarykeys = cf.getGuid();
                    } else {
                        primarykeys += "," + cf.getGuid();
                    }
                }
                bs.setPrimarykeyid(primarykeys);
            }

            result += baseSearchMapper.insertSelective(bs);

        }

        return result;
    }

    /**
     * 通过字段ID返回字段中文描述
     * created on 2018/03/26
     *
     * @param cfgFields  字段信息集合
     * @param strFieldId
     * @return
     */
    private String getFieldCn(List<CfgField> cfgFields, String strFieldId) {
        String fieldtext = "";
        if (cfgFields != null && cfgFields.size() > 0) {
            if (strFieldId != null && !strFieldId.equals("")) {
                String[] searchfield = strFieldId.split(",");
                if (searchfield != null && searchfield.length > 0) {
                    for (String strfield : searchfield) {
                        for (CfgField cf : cfgFields) {
                            if (strfield.equals(cf.getGuid())) {
                                if (fieldtext.equals("")) {
                                    fieldtext = cf.getDfNameCn();
                                } else {
                                    fieldtext += "," + cf.getDfNameCn();
                                }
                            }
                        }
                    }
                }

            }

        }
        return fieldtext;
    }

    /**
     * 通过字段ID返回字段code
     * create on 2018/03/26
     *
     * @param cfgFields  字段信息集合
     * @param strFieldId 字段id
     * @return 字段cdoe
     * @author guoyanfei
     */
    private String getFieldCode(List<CfgField> cfgFields, String strFieldId) {
        String fieldtext = "";
        if (cfgFields != null && cfgFields.size() > 0) {
            if (strFieldId != null && !strFieldId.equals("")) {
                String[] searchfield = strFieldId.split(",");
                if (searchfield != null && searchfield.length > 0) {
                    for (String strfield : searchfield) {
                        for (CfgField cf : cfgFields) {
                            if (strfield.equals(cf.getGuid())) {
                                if (fieldtext.equals("")) {
                                    fieldtext = cf.getDfName();
                                } else {
                                    fieldtext += "," + cf.getDfName();
                                }
                            }
                        }
                    }
                }

            }

        }
        return fieldtext;
    }

    /**
     * show 删除服务中间表(SYS_PRJSERVICE)，全文检索服务配置表(cfg_extsearch),
     * 全文检索服务配置表(base_search) created by date 2018/03/15
     * 接口实现类
     *
     * @param sysPrjservice 中间表服务实体
     * @return 删除条数
     * @author guoyanfei
     */
    @Override
    public Integer deleteSearchInfoByprjservices(SysPrjservice sysPrjservice) {
        Integer result = 0;
        //删除服务中间表
        result += sysPrjserviceMapper.deleteByPrimaryKey(sysPrjservice.getGuid());
        //删除全文检索服务基本信息表
        result += cfgExtsearchMapper.deleteByPrimaryKey(sysPrjservice.getServicecode());
        //删除全文检索服务配置信息表
        result += extBaseSearchMapper.deleteBasesearchByserviceId(sysPrjservice.getServicecode());

        //刷新redis缓存
        redisCacheProjectService.freshProjectServerTree();
        redisCacheComponent.refreshCfgExtSearchRedisCache();
        redisCacheDataBase.refreshFullTextSearchVoRedisCache(sysPrjservice.getServicecode());

        //删除elasticsearch索引库
        deleteESindex(sysPrjservice.getServicecode());

        return result;
    }

    /**
     * 删除elasticsearch索引库数据
     * created on 2018/03/28
     *
     * @param serviceid
     * @author guoyanfei
     */
    private void deleteESindex(String serviceid) {
        ESClient esClient = new ESClient(elasticSerachInfo.address,
                elasticSerachInfo.port, elasticSerachInfo.clustername);
        esClient.deleteIndex(serviceid);
        esClient.closeClient();

    }

    /**
     * show 修改全文检索服务基本信息(CFG_EXTSEARCH表)
     * created on 2018/3/22
     * 实现类
     *
     * @param cfgExtsearch 实体
     * @return 修改条数
     * @author guoyanfei
     */
    @Override
    public Integer updateCfgExtsearch(CfgExtsearch cfgExtsearch) {
        return cfgExtsearchMapper.updateByPrimaryKeySelective(cfgExtsearch);
    }

    /**
     * show 查询所有全文检索基本信息表
     * created on 2018/03/28
     *
     * @return CfgExtSearch实体list集合
     * @author guoyanfei
     */
    @Override
    public List<CfgExtsearch> selectAllCfgExtSearch() {
        return extCfgExtsearchMapper.selectCfgExtsearchByserviceId("");
    }
}
